# coding=utf-8
import os

from dingtalkchatbot.chatbot import DingtalkChatbot

from django.conf import settings


def send(message, at_mobiles=[]):
    # 引用 settings里面配置的钉钉群消息通知的WebHook地址:
    webhook = settings.DINGTALK_WEB_HOOK

    # 初始化机器人小丁, # 方式一：通常初始化方式
    # xiaoding = DingtalkChatbot(webhook)

    # 方式二：勾选“加签”选项时使用（v1.5以上新功能）
    secret = settings.DINGTALK_SECRET
    xiaoding = DingtalkChatbot(webhook, secret=secret)

    # Text消息@所有人
    xiaoding.send_text(msg=('面试通知: %s' % message), at_mobiles=at_mobiles)



import requests
import json


def getAccess_token():
    # appkey = 'dingcf30bzefpgrssqth'
    # appsecret = 'AUL9EK9zud74RH-gbC4wSMPa67srYQ1NFIePT5cLPRFF4H3QQ0Hi5E3qBcfLTaKG'
    appkey = settings.APPKEY
    appsecret = settings.APPSECRET
    url = 'https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (appkey, appsecret)

    headers = {
        'Content-Type': "application/x-www-form-urlencoded"
    }
    data = {'appkey': appkey,
            'appsecret': appsecret}
    r = requests.request('GET', url, data=data, headers=headers)
    access_token = r.json()["access_token"]
    return access_token


def getMedia_id(path=r'C:\recruitment\media\resume_upload\下载_4.docx'):
    access_token = getAccess_token()  # 拿到接口凭证
    # path = r'C:\recruitment\media\resume_upload\下载_4.docx'  # 文件地址
    url = 'https://oapi.dingtalk.com/media/upload?access_token=%s&type=file' % access_token
    try:
        files = {'media': open(path, 'rb')}
    except Exception as e:
        print('e---------------:', e)
    data = {'access_token': access_token,
            'type': 'file'}
    response = requests.post(url, files=files, data=data)
    json = response.json()
    print(path)
    print(json)
    print(files['media'].read())
    return json["media_id"]


def SendFile(path):
    access_token = getAccess_token()
    media_id = getMedia_id(path)
    chatid = settings.CHATID
    # chatid = 'chat51b9258f58adf9bf1ef1fe4223b63a57'  # 通过jsapi工具获取的群聊id
    url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
    header = {
        'Content-Type': 'application/json'
    }
    data = {'access_token': access_token,
            'chatid': chatid,
            'msg': {
                'msgtype': 'file',
                'file': {'media_id': media_id}
            }}
    r = requests.request('POST', url, data=json.dumps(data), headers=header)

    print(os.path.exists(path))
    if os.path.exists(path):
        os.remove(path)


def send_message(content):
    access_token = getAccess_token()
    chatid = settings.CHATID
    url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
    msgtype = 'text'
    values = {
        "chatid": chatid,
        "msgtype": msgtype,
        msgtype: {
            "content": content
        }
    }
    values = json.dumps(values)
    data = requests.post(url, values)
    errmsg = json.loads(data.text)
    print(errmsg)


def SendFile_content(content):
    access_token = getAccess_token()
    print(access_token)
    media_id = getContentMedia_id(content)
    chatid = settings.CHATID
    # chatid = 'chat51b9258f58adf9bf1ef1fe4223b63a57'  # 通过jsapi工具获取的群聊id
    url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
    header = {
        'Content-Type': 'application/json',
        'filename': 'a.docx'
    }
    data = {'access_token': access_token,
            'chatid': chatid,
            'msg': {
                'msgtype': 'file',
                'file': {'media_id': media_id},
            }}
    r = requests.request('POST', url, data=json.dumps(data), headers=header)
    print(r.json())


def getContentMedia_id(content):
    access_token = getAccess_token()  # 拿到接口凭证
    # path = r'C:\recruitment\media\resume_upload\71-Alex YANG个人简历.docx'  # 文件地址
    # f = open(path, 'rb')
    url = 'https://oapi.dingtalk.com/media/upload?access_token=%s&type=file' % access_token
    try:
        files = {
            'media': content,
            # 'media': f,
        }
    except Exception as e:
        pass
    data = {
            'access_token': access_token,
            'type': 'file',
            }

    headers = {
        'filename': 'a.docx'
    }
    response = requests.post(url, files=files, data=data, headers=headers)
    json = response.json()
    return json["media_id"]



